package o2o.web.actions.agent;

import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.agent.AgentManagerMemory;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.agent.UserAgentRelationMemory;
import o2o.cache.order.shop.ShopOrderMemoryMan;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.AgentManagerInfo;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.agent.FENCE_RANGE_TYPE;
import o2o.dao.PO.agent.UserAgentRelation;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.CityAdminOrderCount;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.agent.CityAgentSchoolVO;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.order.ShopOrderCount;
import o2o.dao.VO.shop.AgentOrderCount;
import o2o.company.model.ShopInfo;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.company.SysCityCompanyMan;
import o2o.web.actions.shop.ShopMan;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.*;

// 商圈管理
@Controller
public class CityAgentAction {

    // 获取全部的商圈
    @RequestMapping(method = RequestMethod.POST, value = "user/agent/list/all")
    @ResponseBody
    public String agent_list_all(String token) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        List<CityAgent> list = CityAgentMemory.getInstance().list();
        return AjaxResult.successResult(list);
    }

    //获取商圈列表
    @RequestMapping(method = RequestMethod.POST, value = "/user/agent/list")
    @ResponseBody
    public String agent_list(String token, Integer isLoadAll, String province, String city, String county, String content, Double lat, Double lng) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//        if (user == null) {
//            return AjaxResult.errorLogoutResult();
//        }
        boolean hasLatLng = false;
//        if (ValidateUtil.isAbsDouble(lat) && ValidateUtil.isAbsDouble(lng)) {//按距离排序
//            hasLatLng = true;
//        }
        if (null != lat && null != lng) {//按距离排序
            hasLatLng = true;
        }
        List<CityAgent> list = null;
        if (null != isLoadAll && isLoadAll > 0) {   // 是否加载全部 1 加载全部商圈 0/不传获取当前城市
//            if (user != null && (user.getUserType() == UserType.ADMIN || SysCityCompanyMan.isSuperAdminCompanyUser(user.getUsername()))) {
//                if (ValidateUtil.isNull(city)) {
//                    return AjaxResult.errorResult("城市不能为空");
//                }
//                list = CityAgentMemory.getInstance().listOfCity(city);
//            } else {
//                list = CityAgentMemory.getInstance().list();
//            }
            list = CityAgentMemory.getInstance().list();
        } else {
            if (ValidateUtil.isNull(city)) {
                return AjaxResult.errorResult("城市不能为空");
            }
            list = CityAgentMemory.getInstance().listOfCity(city);
        }

        if (ValidateUtil.isAbsList(list)) {
            List<CityAgentVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                CityAgent cityAgent = list.get(i);
                if (null == cityAgent) {
                    continue;
                }

                if (ValidateUtil.isNotNull(county)) {//如果区不为空检测区
                    if (!county.equalsIgnoreCase(list.get(i).getCounty())) {
                        continue;
                    }
                }

                if (ValidateUtil.isNotNull(content) && (!hasKeyword(cityAgent.getUsername(), content)
                        && !hasKeyword(cityAgent.getName(), content)
                        && !hasKeyword(cityAgent.getProvince(), content)
                        && !hasKeyword(cityAgent.getCity(), content)
                        && !hasKeyword(cityAgent.getCounty(), content)
                        && !hasKeyword(cityAgent.getAddress(), content)
                        && !hasKeyword(cityAgent.getRegion(), content))) {
                    continue;
                }

                CityAgentVO vo = new CityAgentVO();
                try {
                    ObjectUtils.copyPropertiesExclude(cityAgent, vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

                if (hasLatLng) {
                    vo.setDistinct(Geohash.distance(lat, lng, vo.getLat(), vo.getLng()));
                }
                List<String> agentUsernameList = UserAgentRelationMemory.getInstance().usernameListOfAgentId(vo.getId());
                if (ValidateUtil.isAbsList(agentUsernameList)) {
                    UserInfo userInfo = null;
                    for (int j = 0; j < agentUsernameList.size(); j++) {
                        userInfo = UserInfoMemory.getInstance().getUserInfo(agentUsernameList.get(j));
                    }
                    vo.setUserInfo(userInfo);
                }
                voList.add(vo);
            }

            if (hasLatLng) {
                Collections.sort(voList, new Comparator<CityAgentVO>() {
                    public int compare(CityAgentVO arg0, CityAgentVO arg1) {
                        return arg0.getDistinct().compareTo(arg1.getDistinct());//倒叙排列
                    }
                });
            }

            return AjaxResult.successResult(voList.size(), voList);
        }

        return AjaxResult.successResult(0, null);
    }


    @RequestMapping(method = RequestMethod.POST, value = "/agent/fence/modify")
    @ResponseBody
    public String agent_list(String token, Long id, Integer lnglatsType) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (lnglatsType == null || (lnglatsType != FENCE_RANGE_TYPE.BIG && lnglatsType != FENCE_RANGE_TYPE.SMALL)) {
            return AjaxResult.errorResult("请选择操作类型");
        }
        // sup
        if (id == null) {
            StringBuilder sql = new StringBuilder();
            sql.append(" update ").append(PojoTables.CITY_AGENT)
                    .append(" set updateUser ='").append(user.getUsername()).append("'");
            if (lnglatsType == FENCE_RANGE_TYPE.BIG) {
                sql.append(",lnglats = lnglats1");
            } else {
                sql.append(",lnglats = lnglats2");
            }
            sql.append(" where delFlag = 0");
            if (lnglatsType == FENCE_RANGE_TYPE.BIG) {
                sql.append(" and lnglats1 is not  null and lnglats1 !=''");
            } else {
                sql.append(" and lnglats2 is not  null and lnglats2 !=''");
            }
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            }
            CityAgentMemory.getInstance().run();
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_CITY_RELOAD);
            JmsSender.setTopicSender(notify);

            return AjaxResult.successResult();
        } else {
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(id);
            if (cityAgent == null) {
                return AjaxResult.errorResult("未货到商圈信息");
            }
            if (StringUtils.isEmpty(lnglatsType == FENCE_RANGE_TYPE.BIG ? cityAgent.getLnglats1() : cityAgent.getLnglats2())) {
                return AjaxResult.errorResult("您还没有设置" + (lnglatsType == FENCE_RANGE_TYPE.BIG ? "大" : "小") + "商圈");
            }
            if (StringUtils.isNotEmpty(cityAgent.getLnglats()) && cityAgent.getLnglats().equals(
                    lnglatsType == FENCE_RANGE_TYPE.BIG ? cityAgent.getLnglats1() : cityAgent.getLnglats2())) {
                return AjaxResult.successResult();
            }
            // 不一样的
            StringBuilder sql = new StringBuilder();
            sql.append(" update ").append(PojoTables.CITY_AGENT)
                    .append(" set updateUser ='").append(user.getUsername()).append("'");
            sql.append(",lnglats = ").append(lnglatsType == FENCE_RANGE_TYPE.BIG ? "lnglats1" : "lnglats2")
                    .append(" where delFlag = 0 and id  =").append(id);
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败,请稍后重试");
            }
            CityAgentMemory.getInstance().modify(id);
            // 数据同步
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_CITY_UPDATE).setLong01(id);
            JmsSender.setTopicSender(notify);
            return AjaxResult.successResult();
        }
    }

    //获取某一商圈的详细信息
    @RequestMapping(method = RequestMethod.POST, value = "/user/agent/info")
    @ResponseBody
    public String agent_info(Long id) {
        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择要查看的");
        }
//        CityAgent cityAgent = CityAgentMemory.getInstance().getById(id);
//
//        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(cityAgent.getUsername());
//        if (null == shopInfo) {
//            return AjaxResult.errorResult("该代理信息有误，请联系客服");
//        }
//
//
//        CityAgentSchoolVO cityAgentSchoolVO = new CityAgentSchoolVO();
//        try {
//            ObjectUtils.copyPropertiesExclude(cityAgent, cityAgentSchoolVO, null);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        ShopInfoVO shopInfoVO = new ShopInfoVO();
//        try {
//            ObjectUtils.copyPropertiesExclude(shopInfo, shopInfoVO, null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("信息有误，请稍后再试");
//        }
//        cityAgentSchoolVO.setShopInfo(shopInfoVO);
//
//
//        List<GoodsInfoVO> voList = Goods.getRecommendGoodsList(shopInfo.getId(), 1);
//        if (null != voList) {
//            cityAgentSchoolVO.setRecommendGoods(voList);//推荐商品
//        }
//
//        List<AdvertInfoVO> list = AdvertAction.listOfAgent(id, null, true);
//        if (null == list) {
//            cityAgentSchoolVO.setAdvertList(list);
//        }
//
//        CityAgentSchoolVO cityAgentSchoolVO1 = CityAgentMan.getCityAgentDetailInfoById(id);
//
////        List<GoodsInfoVO> voList = new ArrayList<>();
////
////
////        List<GoodsInfo> list = GoodsMemory.getInstance().listOfShop(shopInfo.getId());
////        if (ValidateUtil.isAbsList(list)) {
////            for (int i = 0; i < list.size(); i++) {
////                GoodsInfo info = list.get(i);
////                if (null == info) {
////                    continue;
////                }
////
////                if (0 == 1 - info.getIsRecommend() && 0 == 1 - info.getIsSelling()) {//推荐
////                    continue;
////                }
////
////                GoodsInfoVO vo = new GoodsInfoVO();
////                try {
////                    ObjectUtils.copyPropertiesExclude(info, vo, null);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                    continue;
////                }
////                voList.add(vo);
////            }
////        }
//
////        cityAgentSchoolVO.setRecommendGoods(voList);//推荐商品
//
//
//        return AjaxResult.successResult(cityAgentSchoolVO);

        CityAgentSchoolVO cityAgentSchoolVO1 = CityAgentMan.getCityAgentDetailInfoById(id);

        return AjaxResult.successResult(cityAgentSchoolVO1);
    }

    //添加商圈--管理端
    @RequestMapping(method = RequestMethod.POST, value = "/agent/add")
    @ResponseBody
    public String agent_add(String token, CityAgent info,
                            Integer isAddRelation,  //是否添加代理与商圈的关系 0否 1是
                            Integer isAdmin//是否可以管理商圈里的店铺
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("请先填写信息");
        }

        if (ValidateUtil.isNull(info.getCity())) {
            return AjaxResult.errorResult("城市不能为空");
        }

        //转成英文城市名称
        if (ValidateUtil.isNotNull(info.getCity())) {
            info.setCityEN(JYPinyinHelper.toHanyuPinyin(info.getCity()));
        }

        Long time = DateUtils.getCurrTime();

        //如果账号为空，则随机一个账号
        if (ValidateUtil.isNull(info.getUsername())) {
            info.setUsername(time + "");
        }

        info.setCreateUser(user.getUsername());
        info.setCreateTime(time);
        info.setDelFlag(0);
        info.setId(null);

//        if (ValidateUtil.isNull(info.getUsername())) {
//            return AjaxResult.errorResult("账号不能为空");
//        }

        if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {
            // 电子围栏
            if (null == info.getLnglats()) {
                return AjaxResult.errorResult("请添加围栏");
            }
        } else {
            if (null == info.getLat() || null == info.getLng()) {
                return AjaxResult.errorResult("请输入经纬度");
            }
            String geocode = Geohash.encode(info.getLat(), info.getLng());
            Long areaPoint = Geohash.getArea(info.getLat(), info.getLng());
            info.setGeocode(geocode);
            info.setAreaPoint(areaPoint);
        }
        // 二级骑手一单的价格
        if (!ValidateUtil.isAbsDouble(info.getSecondaryPsMoney())) {
            info.setSecondaryPsMoney(0.0d);
        }
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.CITY_AGENT, info);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("添加代理失败，请稍后再试");
        }
        //更新缓存
        Long agentId = CityAgentMemory.getInstance().add(time);
        // 数据同步
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_CITY_ADD).setLong01(time);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 否添加代理与商圈之前的关系
        if (null != isAddRelation && isAddRelation > 0) {
            String sysCityAdmin = user.getUsername();
            if (user.getUserType() == UserType.SUPER_COMPANY || user.getUserType() == UserType.SUPER_ADMIN) {
                sysCityAdmin = SysCityCompanyMan.getSysCompanyOwnUsername(ValidateUtil.isNull(info.getUsername()) ? sysCityAdmin : info.getUsername());
            } else if (user.getUserType() == UserType.COMPANY || user.getUserType() == UserType.ADMIN) {
                sysCityAdmin = SysCityCompanyMan.getSysCompanyOwnUsername(user.getUsername());
            }
            addUserAgentRelation(agentId, info.getUsername(), sysCityAdmin, user.getUsername());
        }

        // 否添加代理与商圈之前的关系
        if (null != isAdmin && isAdmin > 0) {
            //新增账号
            String adminUsername = info.getUsername();
            if (ValidateUtil.isNull(adminUsername)) {
                return AjaxResult.errorResult("账号不能为空");
            }
            //检测用户是否已经存在
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(adminUsername);
            if (null == userInfo) {//系统中无该用户
                //新建管理员
                UserInfo u = new UserInfo(UserType.ADMIN, adminUsername, info.getName(), null, info.getUsername(), null, null,
                        info.getProvince(), info.getCity(), info.getCounty(), info.getAddress(), user.getUsername());
                try {

                    ResultInfo resultInfo = User.addUser(u, "123456");
                    if (!resultInfo.isSuccess()) {
                        return AjaxResult.errorResult(resultInfo.getError());
                    }
                } catch (Exception e) {
                    return AjaxResult.errorResult("新增失败，请稍后再试");
                }

            } else {
                if (userInfo.getUserType() == UserType.ADMIN || userInfo.getUserType() == UserType.USER || userInfo.getUserType() == UserType.SUPER_ADMIN) {
                    //修改用户类型为管理员
                    if (userInfo.getUserType() == UserType.USER) {
                        StringBuilder sb = new StringBuilder();
                        sb.append("update ").append(PojoTables.UserInfo).append(" set usertype=").append(UserType.ADMIN).append(" where delFlag = 0 and  username='").append(adminUsername).append("'");
                        try {
                            UserDaoSql.getInstance().executeBySql(sb.toString());
                        } catch (SQLException e) {
                            e.printStackTrace();
                            return AjaxResult.errorResult("新增失败，请稍后再试.");
                        }
                        //修改缓存
                        UserInfoMemory.getInstance().modifyUserType(adminUsername, UserType.ADMIN);
                        JMSNotify notify2 = JMSNotify.getInstance().setType(JMSTypeContent.USER_TYPE_MODIFY).setStr01(adminUsername).setInt01(UserType.ADMIN);//o2o.business.jms  MQDataBusiness
                        JmsSender.setTopicSender(notify2);
                    }
                }
            }




            //添加代理与商圈之前的关系
            addUserAgentRelation(agentId, info.getUsername(), adminUsername);
        }

        return AjaxResult.successResult();
    }

    //获取某一商圈的详细信息 只有商圈信息
    @RequestMapping(method = RequestMethod.POST, value = "/admin/agent/info")
    @ResponseBody
    public String agent_info_get(Long id) {
        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择要查看的");
        }

        CityAgentSchoolVO cityAgentSchoolVO1 = CityAgentMan.getCityAgentDetailInfoById(id, false, false, false);
        return AjaxResult.successResult(cityAgentSchoolVO1);
    }

    //修改商圈--管理端
    @RequestMapping(method = RequestMethod.POST, value = "/agent/modify")
    @ResponseBody
    public String agent_modify(String token, CityAgent info,
                               Integer isPower  // 是否有权限修改商圈 0无  1 有
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null == isPower || isPower - 1 != 0) {
            //验证是否有登录权限
            if (!User.getInstance().hasSuperAdminAuth(user.getUserType())) {
                return AjaxResult.errorResult("您没有权限");
            }
        }

        if (ValidateUtil.isNull(info.getCity())) {
            return AjaxResult.errorResult("城市不能为空");
        }

        if (ValidateUtil.isNotID(info.getId())) {
            return AjaxResult.errorResult("请选择要修改的");
        }

        CityAgent cityAgent = CityAgentMemory.getInstance().getById(info.getId());
        if (null == cityAgent) {
            return AjaxResult.errorResult("当前代理不存在，请检查");
        }

        if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {
            // 电子围栏
            if (null == info.getLnglats()) {
                return AjaxResult.errorResult("请添加围栏");
            }
        } else {
            //修改学校代理
            if (null == info.getLat() || null == info.getLng()) {
                return AjaxResult.errorResult("请输入经纬度");
            }
            String geocode = Geohash.encode(info.getLat(), info.getLng());
            Long areaPoint = Geohash.getArea(info.getLat(), info.getLng());
            info.setGeocode(geocode);
            info.setAreaPoint(areaPoint);
        }

        info.setUsername(cityAgent.getUsername());

        if (null == info.getRang()) {
            info.setRang(cityAgent.getRang());
        }

        Double fixedCost = 0d;
        if (null != info.getFixedCost()) {
            fixedCost = info.getFixedCost();
        }
        Double withinDistance = 0d;
        if (null != info.getWithinDistance()) {
            withinDistance = info.getWithinDistance();
        }
        Double oneKmCost = 0d;
        if (null != info.getOneKmCost()) {
            oneKmCost = info.getOneKmCost();
        }

        String fixedWeightCost = "";
        if (null != info.getFixedWeightCost()) {
            fixedWeightCost = ",fixedWeightCost = " + info.getFixedWeightCost();
        }
        String withinWeight = "";
        if (null != info.getWithinWeight()) {
            withinWeight = ",withinWeight=" + info.getWithinWeight();
        }
        String oneKgWeightCost = "";
        if (null != info.getOneKgWeightCost()) {
            oneKgWeightCost = ",oneKgWeightCost=" + info.getOneKgWeightCost();
        }

        // add by zhuwx 2019-2-27
        String psFixedCost = "";
        if (null != info.getPsFixedCost()) {
            psFixedCost = ",psFixedCost=" + info.getPsFixedCost();
        }
        String psWithinDistance = "";
        if (null != info.getPsWithinDistance()) {
            psWithinDistance = ",psWithinDistance=" + info.getPsWithinDistance();
        }
        String psOneKmCost = "";
        if (null != info.getPsOneKmCost()) {
            psOneKmCost = ",psOneKmCost=" + info.getPsOneKmCost();
        }
        String psMaxMoney = "";
        if (null != info.getPsMaxMoney()) {
            psMaxMoney = ",psMaxMoney=" + info.getPsMaxMoney();
        }
        // add by yangtk 2019年5月22日12:07:25 二级骑手每单多少钱
        String secondaryPsMoney = "";
        if (null != info.getSecondaryPsMoney()) {
            secondaryPsMoney = ",secondaryPsMoney=" + info.getSecondaryPsMoney();
        }
        // end

        String lnglats = "";
        if (ValidateUtil.isNotNull(info.getLnglats())) {
            lnglats = info.getLnglats();
        }
        String lnglats1 = "";
        if (ValidateUtil.isNotNull(info.getLnglats1())) {
            lnglats1 = ",lnglats1 = '" + info.getLnglats1() + "'";
        }
        String lnglats2 = "";
        if (ValidateUtil.isNotNull(info.getLnglats2())) {
            lnglats2 = ",lnglats2 = '" + info.getLnglats2() + "'";
        }
        // 区域
        String county = "";
        if (ValidateUtil.isNotNull(info.getCounty())) {
            county = " ,county = '" + info.getCounty() + "'";
        }
        String operatingTime = "";
        if (StringUtils.isNotEmpty(info.getOperatingTime())) {
            operatingTime = ",operatingTime='" + info.getOperatingTime() + "'";
        }
        String isFixedPosition = "";
        if (info.getIsFixedPosition() != null) {
            isFixedPosition = ",isFixedPosition=" + info.getIsFixedPosition() + "";
        }
        String agentMangerStr = "";
        if (StringUtils.isBlank(info.getAgentManagerUsername())) {
            agentMangerStr += ",agentManagerUsername = ''";
        } else {
            AgentManagerInfo managerInfo = AgentManagerMemory.getInstance().get(info.getAgentManagerUsername());
            if (managerInfo != null) {
                agentMangerStr += ",agentManagerUsername = '" + managerInfo.getUsername() + "'";
            }
        }
        // 分成比例
        if (info.getAgentManagerShareRate() != null && info.getAgentManagerShareRate() >= 0) {
            agentMangerStr += ",agentManagerShareRate =" + info.getAgentManagerShareRate();
        }
        // 最小抽佣
        if (info.getMinCharge() != null && info.getMinCharge() >= 0) {
            agentMangerStr += ", minCharge =" + info.getMinCharge();
        }
        String settlementTypeStr = "";
        if (SYS_SETTINGS.IS_OPEN_SHOP_SETTLEMENT == 1) {
            if (info.getSettlementType() != null) {
                settlementTypeStr += ", settlementType =" + info.getSettlementType() + " ";
                if (info.getSettlementType() == 7 && (info.getSettlementDay() == null || info.getSettlementDay() > 7 || info.getSettlementDay() < 1)) {
                    return AjaxResult.errorResult("结算日设置不正确");
                }
                if (info.getSettlementType() == 30 && (info.getSettlementDay() == null || info.getSettlementDay() > 28 || info.getSettlementDay() < 1)) {
                    return AjaxResult.errorResult("结算日设置不正确");
                }
                settlementTypeStr += ",settlementDay =" + info.getSettlementDay() + " ";
            }
        }

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.CITY_AGENT).append(" set name='").append(info.getName()).append("',address='").append(info.getAddress())
                .append("',updateUser='").append(user.getUsername()).append("',lat=").append(info.getLat()).append(",lng=").append(info.getLng())
                .append(",fixedCost=").append(fixedCost).append(",withinDistance=").append(withinDistance).append(",oneKmCost=").append(oneKmCost)
                .append(psFixedCost).append(psWithinDistance).append(psOneKmCost).append(psMaxMoney)
                .append(fixedWeightCost).append(withinWeight).append(oneKgWeightCost).append(county)
                .append(secondaryPsMoney) // 二级骑手每单多少钱
                .append(operatingTime) // 商圈时间经营范围
                .append(isFixedPosition) // 站点是不是固定点
                .append(agentMangerStr) // 区域代理
                .append(settlementTypeStr)      // 计算日
                .append(",geocode='").append(info.getGeocode()).append("',areaPoint=").append(info.getAreaPoint()).append(",rang=").append(info.getRang()).append(",lnglats='").append(lnglats)
                .append("'")
                .append(lnglats1).append(lnglats2)
                .append(" where delFlag = 0 and id = ").append(info.getId());
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }
        CityAgentMemory.getInstance().modify(info.getId());
        // 数据同步
        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_CITY_UPDATE).setLong01(info.getId());
        JmsSender.setTopicSender(notify);

        //修改店铺信息
        modifyShopInfo(info, user.getUsername());
        return AjaxResult.successResult();
    }

    //删除商圈--管理端
    @RequestMapping(method = RequestMethod.POST, value = "/agent/delete")
    @ResponseBody
    public String agent_delete(String token, String ids,
                               Integer isPower  // 是否有权限修改商圈 0无  1 有 (城代管辖自己账号下商圈)
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null == isPower || isPower - 1 != 0) {
            //验证是否有登录权限
            if (!User.hasSuperAdminAuth(user.getUserType())) {
                return AjaxResult.errorResult("您没有权限");
            }
        }

        if (ValidateUtil.isNull(ids)) {
            return AjaxResult.errorResult("请选择要删除的");
        }


        StringBuffer shopIds = new StringBuffer();
        if (ids.indexOf(",") > -1) {
            String[] idArr = ids.split(",");
            if (null != idArr && idArr.length > 0) {
                for (int i = 0; i < idArr.length; i++) {
                    if (ValidateUtil.isNull(idArr[i])) {
                        continue;
                    }
                    Long shopId = getShopIdByAgentId(idArr[i]);
                    if (ValidateUtil.isID(shopId)) {
                        shopIds.append(shopId).append(",");
                    }
                }
            }
        } else {
            Long shopId = getShopIdByAgentId(ids);
            if (ValidateUtil.isID(shopId)) {
                shopIds.append(shopId);
            }
        }

        String sIds = shopIds.toString();
        if (ValidateUtil.isNotNull(sIds) && shopIds.lastIndexOf(",") > 0 && 0 == shopIds.lastIndexOf(",") - (shopIds.length() - 1)) {
            sIds = shopIds.substring(0, shopIds.length() - 1);
        }

        if (ValidateUtil.isNotNull(sIds)) {
            //删除店铺
            ResultInfo resultInfo = ShopMan.deleteShop(sIds, user.getUsername(), user.getUserType());
            if (null != resultInfo && resultInfo.isSuccess()) {
                //删除代理
                StringBuffer sb = new StringBuffer();
                sb.append("update ").append(PojoTables.CITY_AGENT).append(" set delFlag =1 ,updateUser = '").append(user.getUsername())
                        .append("' where delFlag = 0 and id in (").append(ids).append(")");
                try {
                    UserDaoSql.getInstance().executeBySql(sb.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("删除失败，请稍后再试");
                }
            }
        } else {
            //删除代理
            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.CITY_AGENT).append(" set delFlag =1 ,updateUser = '").append(user.getUsername())
                    .append("' where delFlag = 0 and id in (").append(ids).append(")");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("删除失败，请稍后再试");
            }
        }

        if (null != isPower && isPower - 1 == 0) {
            String sysCityAdmin = user.getUsername();
            delUserAgentRelation(ids, sysCityAdmin);
        }

        CityAgentMemory.getInstance().run();
        // 数据同步
        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_CITY_RELOAD);
        JmsSender.setTopicSender(notify);

        return AjaxResult.successResult();
    }


    // 城市代理获取商圈
    @RequestMapping(method = RequestMethod.POST, value = "user/agent/list/v2")
    @ResponseBody
    public String user_agent_list(String token, String username, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }


        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }
        Integer totalCount = 0;
        List<UserAgentRelation> uAList = UserAgentRelationMemory.getInstance().listOfUsername(username);

        ArrayList<CityAgent> voList = null;
        if (ValidateUtil.isAbsList(uAList)) {
            voList = new ArrayList<>();
            for (int i = 0; i < uAList.size(); i++) {
                if (null == uAList.get(i).getAgentId()) {
                    continue;
                }
                CityAgent cityAgent = CityAgentMemory.getInstance().getById(uAList.get(i).getAgentId());
                if (null == cityAgent) {
                    continue;
                }
                voList.add(cityAgent);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }

        return AjaxResult.successResult(0, null);


    }

    // 代理获取商圈信息
    @RequestMapping(method = RequestMethod.POST, value = "user/agent/list/v3")
    @ResponseBody
    public String user_agent_list_v3(String token
            , Long sysAdminId // 代理的id
//            , String province // 省
//            , String city      // 市
//            , String county   // 区
            , Integer isNextLevel // 是否递归下一级的商圈
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (ValidateUtil.isNotID(sysAdminId)) {
            return AjaxResult.errorResult("代理id不能为空");
        }

        Set<Long> agentIdSet = null;
        if (isNextLevel != null && isNextLevel == 1) {
            // 获取他自己以及子递归的商圈
        } else {
            HashSet hashSet = new HashSet<Long>();
            hashSet.add(sysAdminId);
        }
        if (agentIdSet != null && agentIdSet.size() > 0) {
            List<CityAgent> cityAgentList = new ArrayList<>();
            for (Long agentId : agentIdSet) {
                CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
                if (cityAgent != null) {
                    cityAgentList.add(cityAgent);
                }
            }
            if (ValidateUtil.isAbsList(cityAgentList)) {
                return AjaxResult.successResult(cityAgentList.size(), cityAgentList);
            }
        }
        return AjaxResult.successResult(0, null);
    }


    // 城市代理增加商圈
    @RequestMapping(method = RequestMethod.POST, value = "user/agent/add")
    @ResponseBody
    public String user_agent_add(String token, String username, String agentIds) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }

//        if (ValidateUtil.isNull(agentIds)) {
//            return AjaxResult.errorResult("商圈不能为空");
//        }

        // 删除该代理之前商圈
        delUserAgentRelation(null, username);
        //  agentIds 商圈Id
        List<String> agentIdList = new ArrayList<>();
        if (ValidateUtil.isNotNull(agentIds)) {
            String[] agentIdArr = agentIds.split(",");
            if (null != agentIdArr && agentIds.length() > 0) {
                for (int i = 0; i < agentIdArr.length; i++) {
                    if (null == agentIdArr[i]) {
                        continue;
                    }
                    agentIdList.add(agentIdArr[i]);
                }
            }

            if (ValidateUtil.isAbsList(agentIdList)) { // 区域Id集合
                for (int i = 0; i < agentIdList.size(); i++) {
                    Long agentId = Long.parseLong(agentIdList.get(i));
                    addUserAgentRelation(agentId, null, username);
                }
            }
        }
        return AjaxResult.successResult();
    }

    //删除代理与商圈关系--管理端
    @RequestMapping(method = RequestMethod.POST, value = "user/agent/delete")
    @ResponseBody
    public String user_agent_delete(String token, String username, Long agentId) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.errorResult("请选择要删除的");
        }
        if (ValidateUtil.isNull(username)) {
            username = user.getUsername();
        }

        //删除用户与代理关系
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.USER_AGENT_RELATION).append(" set delFlag =1 ,updateUser = '").append(username)
                .append("' where delFlag = 0 and agentId =").append(agentId).append(" and username = ").append(username);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }


        UserAgentRelationMemory.getInstance().deleteUserAgent(username, agentId);
        // 数据同步
        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_AGENT_RELATION_DELETE_BY_AGENT).setStr01(username).setLong01(agentId);
        JmsSender.setTopicSender(notify);

        return AjaxResult.successResult();
    }

    @RequestMapping(method = RequestMethod.POST, value = "agent/manager/agent/select")
    @ResponseBody
    public String user_agent_select(String token) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null || user.getUserType() != UserType.AGENT_MANAGER) {
            return AjaxResult.successResult(0, null);
        }
        AgentManagerInfo info = AgentManagerMemory.getInstance().get(user.getUsername());
        if (info == null) {
            return AjaxResult.successResult(0, null);
        }
        List<CityAgent> cityAgents = CityAgentMemory.getInstance().listByAgentManagerUsername(user.getUsername());
        if (ValidateUtil.isAbsList(cityAgents)) {
            List<Map<String, Object>> list = new ArrayList<>();
            for (CityAgent cityAgent : cityAgents) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", cityAgent.getId());
                map.put("name", cityAgent.getName());
                list.add(map);
            }
            return AjaxResult.successResult(list.size(), list);
        }
        return AjaxResult.successResult();
    }

    // 城市代理下的商圈下拉框
    @RequestMapping(method = RequestMethod.POST, value = "user/agent/select")
    @ResponseBody
    public String user_agent_select(String token, String username,
                                    Integer isNextLevel// 是否递归下一级的商圈
    ) {
        if (ValidateUtil.isNull(username)) {
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
            if (userInfo != null) {
                username = userInfo.getUsername();
            }
        }
        List<CityAgent> voList = new ArrayList<>();
        if (isNextLevel != null && isNextLevel == 1) {
        } else {
            username = SysCityCompanyMan.getSysCompanyOwnUsername(username);
            List<UserAgentRelation> uAList = UserAgentRelationMemory.getInstance().listOfUsername(username);
            if (ValidateUtil.isAbsList(uAList)) {
                for (int i = 0; i < uAList.size(); i++) {
                    if (null == uAList.get(i).getAgentId()) {
                        continue;
                    }
                    CityAgent cityAgent = CityAgentMemory.getInstance().getById(uAList.get(i).getAgentId());
                    if (null == cityAgent) {
                        continue;
                    }
                    voList.add(cityAgent);
                }
            }
        }

        List<Object> re = null;
        if (ValidateUtil.isAbsList(voList)) {
            re = new ArrayList<>();
            for (int i = 0; i < voList.size(); i++) {
                Map<String, Object> data = new HashMap<>();
                data.put("agentId", voList.get(i).getId());
                data.put("agentUsername", voList.get(i).getUsername());
                data.put("name", voList.get(i).getName());
                re.add(data);
            }
            if (ValidateUtil.isAbsList(re)) {
                return AjaxResult.successResult(re.size(), re);
            }
        }
        return AjaxResult.successResult(0, null);
    }


    //---------------
    private Long getShopIdByAgentId(String agentId) {
        try {
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(Long.parseLong(agentId));
            if (null != cityAgent) {
                ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(cityAgent.getUsername());
                if (null != shopInfo) {
                    return shopInfo.getId();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }


    private boolean hasKeyword(String target, String keyword) {
        if (ValidateUtil.isNotNull(target) && target.contains(keyword)) {
            return true;
        }
        return false;
    }


    //修改店铺信息
    private boolean modifyShopInfo(CityAgent agentInfo, String opUsername) {
        //代理信息联动修改
        if (ValidateUtil.isAbsInteger(SYS_SETTINGS.AGENT_IS_SHOP) && 0 == 1 - SYS_SETTINGS.AGENT_IS_SHOP) {
            ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(agentInfo.getUsername());
            if (null != shopInfo) {
                StringBuffer sb = new StringBuffer();
                sb.append("update ").append(PojoTables.ShopInfo).append(" set shopName='").append(agentInfo.getName()).append("',address='").append(agentInfo.getAddress())
                        .append("',updateUser='").append(opUsername).append("',lat=").append(agentInfo.getLat()).append(",lng=").append(agentInfo.getLng())
                        .append(",geocode='").append(agentInfo.getGeocode()).append("',areaPoint=").append(agentInfo.getAreaPoint()).append(" where delFlag = 0 and id = ")
                        .append(shopInfo.getId());
                try {
                    UserDaoSql.getInstance().executeBySql(sb.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                }

                //修改店铺缓存
                ShopMemory.getInstance().modifyById(shopInfo.getId());
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopInfo.getId());
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            }
        }
        return true;
    }

    private Boolean addUserAgentRelation(Long agentId, String agentUsername, String username) {
        return addUserAgentRelation(agentId, agentUsername, username, username);
    }

    // 添加城市代理与商圈的关系
    private Boolean addUserAgentRelation(Long agentId, String agentUsername, String username, String createUser) {

        if (ValidateUtil.isNull(username) || ValidateUtil.isNotAbsLong(agentId)) {
            return false;
        }

        Long time = DateUtils.getCurrTime();
        UserAgentRelation relation = new UserAgentRelation();

        relation.setCreateUser(createUser);
        relation.setCreateTime(time);
        if (ValidateUtil.isNotNull(agentUsername)) {
            relation.setAgentUsername(agentUsername);
        }
        relation.setAgentId(agentId);
        relation.setUsername(username);

        try {
            UserDaoSql.getInstance().insertObj(PojoTables.USER_AGENT_RELATION, relation);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        //更新缓存
        UserAgentRelationMemory.getInstance().add(time);
        // 数据同步
        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_AGENT_RELATION_ADD).setLong01(time);
        JmsSender.setTopicSender(notify);
        return true;
    }

    // 删除城市代理与商圈的关系
    public static Boolean delUserAgentRelation(String agentId, String username) {

        if (ValidateUtil.isNull(username)) {
            return false;
        }

        StringBuffer sb = new StringBuffer();
        String agentIdV2 = "";
        if (ValidateUtil.isNotNull(agentId)) {
            agentIdV2 = " and agentId=" + agentId;
        }
        sb.append("update ").append(PojoTables.USER_AGENT_RELATION).append(" set delFlag =1 ,updateUser = '").append(username)
                .append("' where delFlag = 0 and username ='").append(username).append("'").append(agentIdV2);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        if (ValidateUtil.isNotNull(agentId)) {
            UserAgentRelationMemory.getInstance().deleteUserAgent(username, Long.parseLong(agentId));
            // 数据同步
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_AGENT_RELATION_DELETE_BY_AGENT).setStr01(username).setLong01(Long.parseLong(agentId));
            JmsSender.setTopicSender(notify);
        } else {
            UserAgentRelationMemory.getInstance().deleteByUsername(username);
            // 数据同步
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_AGENT_RELATION_DELETE_BY_USER).setStr01(username);
            JmsSender.setTopicSender(notify);
        }

        return true;
    }

    // 获取某一商圈内订单情况（订单监控） // yunsong 在用
    @RequestMapping("/agent/shop/order/count")
    @ResponseBody
    public String getShopOrderInfo(String token, Long agentId, Long strTime, Long endTime) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否是管理员
//        if(!User.hasAdminAuth( user.getUserType() )) {
//            return AjaxResult.errorResult("您没有操作权限");
//        }
        if (!ValidateUtil.isID(agentId)) {
            // 验证管理员是否有商圈
            CityAgent getCityAgent = CityAgentMemory.getInstance().getByUsername(user.getUsername());
            if (null == getCityAgent || null == getCityAgent.getId()) {
                return AjaxResult.errorResult("暂时没有查到您的商圈");
            }
            agentId = getCityAgent.getId();
        }
        // 通过商圈获取该商圈下的店铺
        List<Long> shopsIdList = ShopAgentRelationMemory.getInstance().listOfAgentId(agentId);
        // 商圈代理的指定店铺
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (null != shopInfo && ValidateUtil.isID(shopInfo.getId())) {
            if (ValidateUtil.isAbsList(shopsIdList)) {
                boolean isExist = false;
                for (Long l : shopsIdList) {
                    if (shopInfo.getId() == l) {
                        isExist = true;
                    }
                }
                if (!isExist) {
                    shopsIdList.add(shopInfo.getId());
                }
            } else {
                shopsIdList.add(shopInfo.getId());
            }
        }

        if (null == shopsIdList || shopsIdList.size() < 1) {
            return AjaxResult.errorResult("您选择的商圈内还没有店铺");
        }
        List<ShopOrderCount> list = new ArrayList<>();
        for (Long l : shopsIdList) {
            if (!ValidateUtil.isID(l)) {
                continue;
            }
            ShopOrderCount shopOrderCount = getShopOrderDetail(l, agentId, strTime, endTime);
            if (null == shopOrderCount) {
                continue;
            }
            list.add(shopOrderCount);
        }
        if (ValidateUtil.isAbsList(list)) {
            Collections.sort(list, new Comparator<ShopOrderCount>() {
                @Override
                public int compare(ShopOrderCount o1, ShopOrderCount o2) {
                    return o2.getOverTimeOrderCount() > o1.getOverTimeOrderCount() ? 1 : -1;
                }
            });
        }
        return AjaxResult.successResult(list.size(), list);
    }

    // 获取店铺订单 数量跟踪
    private ShopOrderCount getShopOrderDetail(Long shopId, Long agentId, Long strTime, Long endTime) {
        List<OrderInfo> listOrderInfoByShopId = ShopOrderMemoryMan.listOfOrderType(shopId, null, strTime, endTime);
        // 超时未接单
        int overTimeOrderCount = 0;
        //新订单 状态为 ORDER_STATUS.PAYED
        int newOrderCount = 0;
        //未取订单
        int notTakenCount = 0;
        if (null != listOrderInfoByShopId && listOrderInfoByShopId.size() > 0) {
            for (OrderInfo info : listOrderInfoByShopId) {
//                if(ORDER_STATUS.PAYED == info.getOrderStatus()){
//                    //超时系统自动取消订单
//                    Long time = DateUtils.getCurrTime();
//                    if(info.getPayTime() != null && (time-info.getPayTime()) > 5*60*1000){
//                        overTimeOrderCount ++;
//                    }
//                }else
                if (info.getOrderStatus() == ORDER_STATUS.PAYED) {
                    //用户已支付，商家未接单
                    newOrderCount++;
                    // 超时未接订单 是指用户付款后 商家超过5分钟未接订单；
                    Long time = DateUtils.getCurrTime();
                    if (info.getPayTime() != null && (time - info.getPayTime()) > 5 * 60 * 1000) {
                        overTimeOrderCount++;
                    }
                } else if (info.getOrderStatus() == ORDER_STATUS.SHOP_SURE  //商家已接单
                        || info.getOrderStatus() == ORDER_STATUS.SHOP_READY //商家已经完成备货
                        || info.getOrderStatus() == ORDER_STATUS.SHOP_PUSH_GOODS //商家已确认发货
                        || info.getOrderStatus() == ORDER_STATUS.POSTMAN_PULL_GOODS //配送员已取货
                        || info.getOrderStatus() == ORDER_STATUS.PEISONG //配送员已取货，配送货物路上
                        || info.getOrderStatus() == ORDER_STATUS.POSTMAN_ZHIDING //已指定配送员
                        || info.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE //配送接单
                ) {
                    //未取订单
                    notTakenCount++;
                }
            }
        }
        ShopOrderCount shopOrderCount = null;
        //店铺被删除  与商圈的关系可能存在
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);

        if (shopInfo == null) {
            return shopOrderCount;
        } else {
            shopOrderCount = new ShopOrderCount();
            try {
                ObjectUtils.copyPropertiesExclude(shopInfo, shopOrderCount);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        shopOrderCount.setAgentId(agentId);
        shopOrderCount.setNewOrderCount(newOrderCount);
        shopOrderCount.setNotTakenCount(notTakenCount);
        shopOrderCount.setOverTimeOrderCount(overTimeOrderCount);
        return shopOrderCount;
    }

    // 获取商圈 店铺信息
    private List<ShopOrderCount> get_agent_order_count(Long agentId, Long strTime, Long endTime) {
        List<ShopOrderCount> shopOrderCounts = new ArrayList<>();
        if (null == agentId) {
            return shopOrderCounts;
        }
        // 有商圈获取商圈内得店铺
        List<Long> shopsIdList = ShopAgentRelationMemory.getInstance().listOfAgentId(agentId);
        if (null == shopsIdList || shopsIdList.size() < 1) {
            return shopOrderCounts;
        }
        for (Long l : shopsIdList) {
            if (!ValidateUtil.isID(l)) {
                continue;
            }
            ShopOrderCount shopOrderCount = getShopOrderDetail(l, agentId, strTime, endTime);
            if (null == shopOrderCount) {
                continue;
            }
            shopOrderCounts.add(shopOrderCount);
        }
        return shopOrderCounts;
    }

    // 获取该代理下 所有商圈信息 代理1->list<商圈>
    public List<AgentOrderCount> get_cityAdmin_order_count(String username, Long strTime, Long endTime) {
        // 代理下 商圈
        List<AgentOrderCount> agentOrderList = new ArrayList<>();
        // 由代理账号获取代理信息
//        CityAgent cityAgent = CityAgentMemory.getInstance().getByUsername(username);
//        if (null == cityAgent) {
//            return agentOrderList;
//        }
        //代理账号下的 所有商圈
        List<UserAgentRelation> userAgentRelations = UserAgentRelationMemory.getInstance().listOfUsername(username);
        CityAgent cityAgent = CityAgentMemory.getInstance().getByUsername(username);

        // 没有商圈
        if (null == userAgentRelations || userAgentRelations.size() < 1) {
            return agentOrderList;
        }
        // 商圈
        for (UserAgentRelation userAgentRelation : userAgentRelations) {
            if (null == userAgentRelation) {
                continue;
            }
            AgentOrderCount agentOrderCount = new AgentOrderCount();
            if (null != cityAgent) {
                try {
                    ObjectUtils.copyPropertiesExclude(cityAgent, agentOrderCount, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            agentOrderList.add(agentOrderCount);
        }
        // 将shopcount 添加所属商圈
        for (AgentOrderCount agentCount : agentOrderList) {
            if (null == agentCount || agentCount.getId() == null) {
                continue;
            }
            List<ShopOrderCount> shopOrderCounts = get_agent_order_count(agentCount.getId(), strTime, endTime);
            if (null == shopOrderCounts) {
                continue;
            }
            agentCount.setShopOrderCounts(shopOrderCounts);
        }
        return agentOrderList;
    }


    // 城市：城市代理跟踪城市下商圈的id
    @RequestMapping("/agent/city/order/count")
    @ResponseBody
    public String getCityAgentOrder(String token
            , String province // 省
            , String city   // 市
            , String county // 区
            , String cityAdminUsername // 城市代理Id
            , Long agentId // 商圈id
            , Long strTime // 开始时间
            , Long endTime // 结束时间
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否是管理员 城市代理？？？ 待定
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("城市不能为空");
        }
        // 商圈
//        List<AgentOrderCount> voList = new ArrayList<>();
        //城市下商圈订单
        List<CityAdminOrderCount> cityAdminOrderCounts = new ArrayList<>();

        if (ValidateUtil.isID(agentId)) {
            // 城市代理信息
            CityAdminOrderCount cityAdminOrderCount = new CityAdminOrderCount();
            // 成带
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(cityAdminUsername);
            CityAgent cityAgent = CityAgentMemory.getInstance().getByUsername(cityAdminUsername);
            AgentOrderCount agentOrderCount = new AgentOrderCount();

            // 城市代理详细信息
            if (null != userInfo) {
                try {
                    ObjectUtils.copyPropertiesExclude(userInfo, cityAdminOrderCount, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 商圈详细信息
            if (null != cityAgent) {
                try {
                    ObjectUtils.copyPropertiesExclude(cityAgent, agentOrderCount, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 指定 商圈下的下的
            List<ShopOrderCount> list = get_agent_order_count(agentId, strTime, endTime);
            agentOrderCount.setShopOrderCounts(list);
//            if (cityAgent == null) {
//                return AjaxResult.errorResult("暂无此商圈");
//            }

//            AgentOrderCount agentOrderCount = new AgentOrderCount();
//            if(null != cityAgent){
//                try {
//                    ObjectUtils.copyPropertiesExclude(cityAgent, agentOrderCount, null);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            // 商圈
////            List<ShopOrderCount> shopOrderCounts = new ArrayList<>();
//            // 获取某一商圈 的订单跟踪
//
//            CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
//            if (cityAgent == null) {
//                return AjaxResult.errorResult("暂无此商圈");
//            }
//            ShopOrderCount shopAgentCount = new ShopOrderCount();
//            try {
//                ObjectUtils.copyPropertiesExclude(cityAgent, shopAgentCount, null);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            if (null == shopAgentCount) {
//                return AjaxResult.errorResult("出错了~请稍后重试");
//            }
//            shopOrderCounts.setShopOrderCounts(list);
//            agentOrderList.add(shopAgentCount);
            List<AgentOrderCount> agentOrderCounts = new ArrayList<>();
            agentOrderCounts.add(agentOrderCount);
            cityAdminOrderCount.setAgentOrderCounts(agentOrderCounts);
            cityAdminOrderCounts.add(cityAdminOrderCount);
        } else if (ValidateUtil.isNotNull(cityAdminUsername)) {
            cityAdminOrderCounts = new ArrayList<>();
            // 获取指定城市代理下的订单监控
            // 代理信息
            CityAdminOrderCount cityAdminOrderCount = new CityAdminOrderCount();
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(cityAdminUsername);
            if (null != userInfo) {
                try {
                    ObjectUtils.copyPropertiesExclude(userInfo, cityAdminOrderCount, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 代理商圈信息
            List<AgentOrderCount> agentOrderCounts = get_cityAdmin_order_count(cityAdminUsername, strTime, endTime);
            // 将 代理的商圈 放在代理下
            cityAdminOrderCount.setAgentOrderCounts(agentOrderCounts);
            // 将代理加入到城市下
            cityAdminOrderCounts.add(cityAdminOrderCount);
        } else {
            cityAdminOrderCounts = new ArrayList<>();

        }
        return AjaxResult.successResult(cityAdminOrderCounts.size(), cityAdminOrderCounts);
    }

}
